package org.wlw.web.servlet;

import org.wlw.web.anno.Resource;
import org.wlw.web.models.User;
import org.wlw.web.service.IUserService;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/admin/user")
public class UserServlet extends BaseServlet{
    private IUserService userService;

    @Resource
    public void setUserService(IUserService userService) {
        this.userService = userService;
    }

    public String index(HttpServletRequest request, HttpServletResponse response) {
        request.setAttribute("users",userService.find(null));
        return "user/list";
    }

    public String add(HttpServletRequest request,HttpServletResponse response) {
        return "user/add";
    }

    public String addAction(HttpServletRequest request,HttpServletResponse response) {
        User user = new User();
        user.setUsername(request.getParameter("username"));
        user.setNickname(request.getParameter("nickname"));
        user.setPassword(request.getParameter("password"));
        userService.add(user);
        return getRedirectUrl("/admin/user");
    }

    public String delete(HttpServletRequest request,HttpServletResponse response) {
//        System.out.println("----------------"+request.getParameter("id"));
        int id = Integer.parseInt(request.getParameter("id"));
        userService.delete(id);
        return getRedirectUrl("/admin/user");
    }

    public String update(HttpServletRequest request,HttpServletResponse response) {
        int id = Integer.parseInt(request.getParameter("id"));
        User user = userService.load(id);
        request.setAttribute("user",user);
        return "user/update";
    }

    public String updateAction(HttpServletRequest request,HttpServletResponse response) {
        int id = Integer.parseInt(request.getParameter("id"));
        User user = userService.load(id);
        user.setNickname(request.getParameter("nickname"));
        user.setPassword(request.getParameter("password"));
        userService.update(user);
        return getRedirectUrl("/admin/user");
    }
}
